<template>
  <div class="">
    <!-- 顶部控制栏 -->
    <el-card class="control-panel">

      <div class="time-control">
        <div class="host-info">
          <span class="label">主机IP:</span>
          <span class="value">{{ hostIp }}</span>
        </div>
        <el-select v-model="timeRange" size="small" @change="handleTimeRangeChange">
          <el-option label="1小时" value="1h"></el-option>
          <el-option label="6小时" value="6h"></el-option>
          <el-option label="12小时" value="12h"></el-option>
          <el-option label="24小时" value="24h"></el-option>
        </el-select>
        <el-date-picker
          v-model="timeSpan"
          type="datetimerange"
          size="small"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :picker-options="pickerOptions"
          @change="handleTimeSpanChange"
        >
        </el-date-picker>
        <el-button
          type="primary"
          size="small"
          icon="el-icon-refresh"
          @click="refreshData"
          :loading="loading"
        >刷新</el-button>
      </div>
    </el-card>

    <!-- 监控图表区域 -->
    <div class="charts-container">
      <!-- CPU使用率 -->
      <el-card class="chart-card">
        <div class="chart-header">
          <h3>CPU使用率 (单位: %)</h3>
          <el-tooltip content="CPU使用率说明" placement="top">
            <i class="el-icon-question"></i>
          </el-tooltip>
        </div>
        <div class="chart-content" ref="cpuChart"></div>
      </el-card>

      <!-- 内存使用率 -->
      <el-card class="chart-card">
        <div class="chart-header">
          <h3>内存使用率 (单位: %)</h3>
          <el-tooltip content="内存使用率说明" placement="top">
            <i class="el-icon-question"></i>
          </el-tooltip>
        </div>
        <div class="chart-content" ref="memoryChart"></div>
      </el-card>

      <!-- 磁盘使用情况 -->
      <el-card class="chart-card">
        <div class="chart-header">
          <h3>磁盘使用 (单位: G)</h3>
          <el-tooltip content="磁盘使用说明" placement="top">
            <i class="el-icon-question"></i>
          </el-tooltip>
        </div>
        <div class="chart-content" ref="diskChart"></div>
      </el-card>

      <!-- 磁盘读写速度 -->
      <el-card class="chart-card">
        <div class="chart-header">
          <h3>磁盘读写速度 (M/s)</h3>
          <el-tooltip content="磁盘读写速度说明" placement="top">
            <i class="el-icon-question"></i>
          </el-tooltip>
        </div>
        <div class="chart-content" ref="diskSpeedChart"></div>
      </el-card>

      <!-- 读写请求数 -->
      <el-card class="chart-card">
        <div class="chart-header">
          <h3>读写请求数 (IOPS)</h3>
          <el-tooltip content="读写请求数说明" placement="top">
            <i class="el-icon-question"></i>
          </el-tooltip>
        </div>
        <div class="chart-content" ref="iopsChart"></div>
      </el-card>

      <!-- 带宽使用 -->
      <el-card class="chart-card">
        <div class="chart-header">
          <h3>带宽使用 (单位Kbit/s)</h3>
          <el-tooltip content="带宽使用说明" placement="top">
            <i class="el-icon-question"></i>
          </el-tooltip>
        </div>
        <div class="chart-content" ref="bandwidthChart"></div>
      </el-card>

      <!-- TCP连接数 -->
      <el-card class="chart-card">
        <div class="chart-header">
          <h3>TCP连接数 (个)</h3>
          <el-tooltip content="TCP连接数说明" placement="top">
            <i class="el-icon-question"></i>
          </el-tooltip>
        </div>
        <div class="chart-content" ref="tcpChart"></div>
      </el-card>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import {GetinstanceBatch} from "@/api/resell/orderinstance";
import fa from "element-ui/src/locale/lang/fa";

export default {
  name: 'ServerMonitor',
  props: {
    currentResource: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      hostIp: this.currentResource.other4,
      timeRange: '1h',
      timeSpan: [],
      loading: false,
      refreshTimer: null,
      charts: {},
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一小时',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一天',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24)
              picker.$emit('pick', [start, end])
            }
          }
        ]
      },
      statelist: [],
      chatCupX:[],
      chatCupY:[],
      chatBandWidthX:[],
      chatBandWidthY:[],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        resourceId:null,
        projectId:null,
        other1: null,
        other2: null,
        other3: null,
        other4: null,
        other5: null,
        ucode:null,
        ucodeiam:null,
        upsw:null,
        regionCode:null,

      },

    }
  },
  methods: {
    initCharts() {
      // 初始化所有图表
      const chartRefs = ['cpuChart', 'memoryChart', 'diskChart', 'diskSpeedChart',
        'iopsChart', 'bandwidthChart', 'tcpChart']

      chartRefs.forEach(ref => {
        if (this.charts[ref]) {
          this.charts[ref].dispose()
        }
        this.charts[ref] = echarts.init(this.$refs[ref])
      })

      this.updateCharts()
    },
    updateCharts() {
      // 更新CPU图表
      this.charts.cpuChart.setOption({
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: this.chatCupX,
        },
        yAxis: {
          type: 'value',
          max: 100,
          min: 0
        },
        dataZoom: [
          {
            type: 'inside',
            start: 0,
            end: 100
          },
          {
            start: 0,
            end: 100
          }
        ],
        series: [{
          name: 'CPU使用率',
          type: 'line',
          smooth: true,
          data: this.chatCupY,
          areaStyle: {
            opacity: 0.1
          },
          lineStyle: {
            width: 1
          },
          itemStyle: {
            color: '#409EFF'
          }
        }]
      })

      // 更新内存图表
      this.charts.memoryChart.setOption({
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: this.generateTimeData()
        },
        yAxis: {
          type: 'value',
          max: 100,
          min: 0
        },
        dataZoom: [
          {
            type: 'inside',
            start: 0,
            end: 100
          },
          {
            start: 0,
            end: 100
          }
        ],
        series: [{
          name: '内存使用率',
          type: 'line',
          smooth: true,
          data: this.generateRandomData(90, 80),
          areaStyle: {
            opacity: 0.1
          },
          lineStyle: {
            width: 1
          },
          itemStyle: {
            color: '#67C23A'
          }
        }]
      })

      // 更新磁盘使用图表
      this.charts.diskChart.setOption({
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c}G ({d}%)'
        },
        legend: {
          orient: 'horizontal',
          bottom: 10,
          data: ['已使用', '未使用']
        },
        series: [
          {
            name: '磁盘使用',
            type: 'pie',
            radius: ['50%', '70%'],
            avoidLabelOverlap: false,
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '20',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: [
              { value: 24.40, name: '已使用', itemStyle: { color: '#67C23A' } },
              { value: 15.60, name: '未使用', itemStyle: { color: '#909399' } }
            ]
          }
        ]
      })

      // 更新磁盘速度图表
      this.charts.diskSpeedChart.setOption({
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          }
        },
        legend: {
          data: ['读取速度', '写入速度']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: this.generateTimeData()
        },
        yAxis: {
          type: 'value'
        },
        dataZoom: [
          {
            type: 'inside',
            start: 0,
            end: 100
          },
          {
            start: 0,
            end: 100
          }
        ],
        series: [
          {
            name: '读取速度',
            type: 'line',
            smooth: true,
            data: this.generateRandomData(0.08, 0.02),
            itemStyle: {
              color: '#409EFF'
            }
          },
          {
            name: '写入速度',
            type: 'line',
            smooth: true,
            data: this.generateRandomData(0.03, 0.02),
            itemStyle: {
              color: '#67C23A'
            }
          }
        ]
      })

      // 更新IOPS图表
      this.charts.iopsChart.setOption({
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          }
        },
        legend: {
          data: ['读取IOPS', '写入IOPS']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: this.generateTimeData()
        },
        yAxis: {
          type: 'value'
        },
        dataZoom: [
          {
            type: 'inside',
            start: 0,
            end: 100
          },
          {
            start: 0,
            end: 100
          }
        ],
        series: [
          {
            name: '读取IOPS',
            type: 'line',
            smooth: true,
            data: this.generateRandomData(0.6, 0.3),
            itemStyle: {
              color: '#409EFF'
            }
          },
          {
            name: '写入IOPS',
            type: 'line',
            smooth: true,
            data: this.generateRandomData(2.8, 2.4),
            itemStyle: {
              color: '#67C23A'
            }
          }
        ]
      })

      // 更新带宽图表
      this.charts.bandwidthChart.setOption({
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          }
        },
        legend: {
          data: ['入方向', '出方向']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: this.chatBandWidthX
        },
        yAxis: {
          type: 'value'
        },
        dataZoom: [
          {
            type: 'inside',
            start: 0,
            end: 100
          },
          {
            start: 0,
            end: 100
          }
        ],
        series: [
          {
            name: '入方向',
            type: 'line',
            smooth: true,
            data: this.chatBandWidthY,
            itemStyle: {
              color: '#409EFF'
            }
          },
          {
            name: '出方向',
            type: 'line',
            smooth: true,
            data: this.chatBandWidthY,
            itemStyle: {
              color: '#67C23A'
            }
          }
        ]
      })

      // 更新TCP连接数图表
      this.charts.tcpChart.setOption({
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: this.generateTimeData()
        },
        yAxis: {
          type: 'value'
        },
        dataZoom: [
          {
            type: 'inside',
            start: 0,
            end: 100
          },
          {
            start: 0,
            end: 100
          }
        ],
        series: [{
          name: 'TCP连接数',
          type: 'line',
          smooth: true,
          data: this.generateRandomData(65, 55),
          itemStyle: {
            color: '#409EFF'
          }
        }]
      })
    },
    generateTimeData() {
      const times = []
      const now = new Date()
      for (let i = 0; i < 60; i++) {
        const time = new Date(now - (60 - i) * 60000)
        times.push(this.formatTime(time))
      }
      return times
    },
    formatTime(date) {
      const hours = date.getHours().toString().padStart(2, '0')
      const minutes = date.getMinutes().toString().padStart(2, '0')
      return `${hours}:${minutes}`
    },
    generateRandomData(max, min = 0) {
      const data = []
      for (let i = 0; i < 60; i++) {
        data.push(+(min + Math.random() * (max - min)).toFixed(2))
      }
      return data
    },
    handleTimeRangeChange() {
      this.refreshData()
    },
    handleTimeSpanChange() {
      this.refreshData()
    },
    refreshData() {
      this.loading = true
      this.queryParams.resourceId = this.currentResource.resourceId;
      this.queryParams.projectId = this.currentResource.projectId;

      this.queryParams.ucode = this.currentResource.ucode;
      this.queryParams.ucodeiam = this.currentResource.ucodeiam;
      this.queryParams.upsw = this.currentResource.upsw;
      this.queryParams.regionCode = this.currentResource.regionCode;
      this.queryParams.other1 = '1';
      this.queryParams.other2 = 'average';
      GetinstanceBatch(this.queryParams).then(response => {
        this.statelist = [];
        this.statelist = response.rows;
        this.statelist.forEach(element => {
          if (element.other1 == "cpu_util") {
            var tancelist = element.showinstance;
            tancelist.forEach(tval => {
              this.chatCupY.push(tval.other1);
              this.chatCupX.push(tval.other2);
            });
          }
        });
        this.statelist.forEach(element => {
          if (element.other1 == "disk_write_bytes_rate") {
            var tancelist = element.showinstance;
            tancelist.forEach(tval => {
              this.chatBandWidthY.push(tval.other1);
              this.chatBandWidthX.push(tval.other2);
              // other2fw.push(this.parseTime(element.other2, '{m}-{d}'))
            });
          }
        });


        this.updateCharts();
        this.loading = false
      });

    },
    startAutoRefresh() {
      this.refreshTimer = setInterval(() => {
        this.refreshData()
      }, 60000) // 每分钟刷新一次
    },
    stopAutoRefresh() {
      if (this.refreshTimer) {
        clearInterval(this.refreshTimer)
        this.refreshTimer = null
      }
    },
    handleResize() {
      Object.values(this.charts).forEach(chart => {
        chart && chart.resize()
      })
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initCharts()
      window.addEventListener('resize', this.handleResize)
    })
    this.startAutoRefresh()
  },
  beforeDestroy() {
    this.stopAutoRefresh()
    window.removeEventListener('resize', this.handleResize)
    // 销毁图表实例
    Object.values(this.charts).forEach(chart => {
      chart && chart.dispose()
    })
  }
}
</script>

<style scoped>
.monitor-page {
  padding: 20px;
  background: #f5f7fa;
  min-height: 100vh;
}

.control-panel {
  background: #fff;
  padding: 16px;
  border-radius: 4px;
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.05);
}

.host-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.host-info .label {
  color: #606266;
  font-weight: 500;
}

.host-info .value {
  color: #1e69ec;
  font-weight: 500;
}

.time-control {
  display: flex;
  gap: 12px;
  align-items: center;
}

.charts-container {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
}

.chart-card {
  background: #fff;
  border-radius: 4px;
  padding: 16px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.05);
}

.chart-header {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 1px solid #ebeef5;
}

.chart-header h3 {
  margin: 0;
  font-size: 14px;
  color: #303133;
}

.chart-header i {
  margin-left: 8px;
  color: #909399;
  cursor: help;
}

.chart-content {
  height: 300px;
}

/* 响应式布局 */
@media screen and (max-width: 1200px) {
  .charts-container {
    grid-template-columns: 1fr;
  }
}

@media screen and (max-width: 768px) {
  .monitor-page {
    padding: 10px;
  }

  .control-panel {
    flex-direction: column;
    gap: 16px;
  }

  .time-control {
    flex-direction: column;
    width: 100%;
  }

  .time-control .el-select,
  .time-control .el-date-picker {
    width: 100%;
  }

  .chart-content {
    height: 250px;
  }
}
</style>
